package org.lzy.shop.viewmodel.repository

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.lzy.shop.base.BaseResponse
import org.lzy.shop.network.ApiException
import org.lzy.shop.network.ERROR
import org.lzy.shop.util.ErrorHandler

/**
 * Repository基类，提供通用的网络请求处理逻辑
 */
open class BaseRepository {
    /**
     * 安全地执行网络请求并处理异常
     */
    protected suspend fun <T> safeApiCall(
        errorMessage: String = ERROR.UNKNOWN.errMsg,
        call: suspend () -> T
    ): T? {
        return withContext(Dispatchers.IO) {
            try {
                call()
            } catch (e: Exception) {
                // 统一处理异常
                throw ErrorHandler.handleException(e)
            }
        }
    }

    /**
     * 处理BaseResponse类型的响应
     */
    protected fun <T> handleResponse(response: BaseResponse<T>): T {
        if (response.isFailed()) {
            // 可以根据返回的code映射到ERROR枚举中的错误
            throw ApiException(response.code, response.message)
        }
        return response.data
    }
}